//
//  ApprenticeListViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/8/23.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "ApprenticListCell.h"
#import "ApprenticHeadView.h"
#import "HMSegmentedControl.h"

#import "ApprenticeListViewController.h"

@interface ApprenticeListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) HMSegmentedControl *segmentedControl;

@property (strong, nonatomic) UITableView *tableview;

@property (strong, nonatomic) ApprenticHeadView *headView;

@property (nonatomic, strong) ApprenticeHeadModel *headModel;

@property (nonatomic, strong) NSMutableArray <ApprenticeModel *>*ApprenticeListArray;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, assign) PPApprenticType type;

@end

@implementation ApprenticeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self request_ApprenticeList];
}

- (void)refresh {
    self.pageNum = 0;
    self.pageSize = 1000;
}

- (void)initView {

    self.title = @"师徒";
    self.type = PPApprenticType_all;
    self.view.backgroundColor = UIColorHex(0xf1f1f1);

    self.headView  =  [[NSBundle mainBundle] loadNibNamed:@"ApprenticHeadView"owner:nil options:nil].firstObject;

    [self.view addSubview:self.headView];
    [self.view addSubview:self.segmentedControl];
    [self.view addSubview:self.tableview];

    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(110);
    }];

    self.segmentedControl.frame = CGRectMake(0 , 110, TTScreenWidth, 50);

    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.top.mas_equalTo(self.segmentedControl.mas_bottom);
    }];

    [self.tableview reloadData];

    WEAKSELF
    [self.segmentedControl setIndexChangeBlock:^(NSInteger index) {

        [weakSelf refresh];
        weakSelf.type = (PPApprenticType)index;
        [weakSelf request_ApprenticeList];
    }];
}

- (void)request_ApprenticeList {

    NSDictionary *dic = @{}.mutableCopy;
    [dic setValue:@"1" forKey:@"curPage"];
    [dic setValue:@"10" forKey:@"pageSize"];

    switch (self.type) {
        case PPApprenticType_all:{
        } break;
        case PPApprenticType_unGraduation:{
            [dic setValue:@"0" forKey:@"canExtracted"];
        } break;
        case PPApprenticType_graduated:{
            [dic setValue:@"1" forKey:@"canExtracted"];
        } break;

        default:
            break;
    }

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_POPULARIZE_APPRENTICE_LIST];

    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [[TTNoResultManager shareManager] hideNoResultWithView:self.tableview];

        if ([data isKindOfClass:[NSDictionary class]]) {

            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {

                    self.headModel.itemUserName = [resultDic valueForKey:@"userName"];
                    self.headModel.itemAvatar = [resultDic valueForKey:@"avatar"];
                    self.headModel.itemParentUsername = [resultDic valueForKey:@"parentUsername"];
                    self.headModel.itemPupilCount = [resultDic valueForKey:@"pupilCount"];
                    self.headModel.itemTodayPupilCount = [resultDic valueForKey:@"todayPupilCount"];
                    self.headModel.itemUnGraduateCount = [resultDic valueForKey:@"unGraduateCount"];
                    self.headModel.itemGraduateCount = [resultDic valueForKey:@"graduateCount"];

                    [self.headView fillHeaderWithModel:self.headModel];

                    NSArray *pupilResList = [resultDic valueForKey:@"pupilResList"];
                    if ([pupilResList isKindOfClass:[NSArray class]]) {

                        if (self.pageNum == 0) {
                            [self.ApprenticeListArray removeAllObjects];
                        }

                        for (int i = 0; i<pupilResList.count; i++) {

                            NSDictionary *pupilRes = pupilResList[i];
                            ApprenticeModel *model = [[ApprenticeModel alloc] init];


                            double time = [[pupilRes valueForKey:@"createTime"] doubleValue];
                            model.itemTime = [Utilities getTimeFromTimestamp:time];
//                            model.itemTime = [pupilRes valueForKey:@"createTime"];
                            model.itemApprenticeName = [pupilRes valueForKey:@"userName"];
                            model.extracted = [[pupilRes valueForKey:@"extracted"] boolValue];

                            model.acquirableMoney = [[pupilRes valueForKey:@"acquirableMoney"] stringValue];

                            [self.ApprenticeListArray addObject:model];
                        }

                        if (self.pageNum == 0 && pupilResList.count == 0) {
                            [[TTNoResultManager shareManager] showNoResultWithStateInView:self.tableview errorCode:kTTViewStateNoData btnTitle:@"" didPressButton:^{
                                [self request_ApprenticeList];

                            }];
                        }
                    }

                } else {

                    [[TTNoResultManager shareManager] showNoResultWithStateInView:self.tableview errorCode:kTTViewStateNoData btnTitle:@"" didPressButton:^{
                        [self request_ApprenticeList];

                    }];
                }


                self.segmentedControl.sectionTitles = @[
                                                        [NSString stringWithFormat:@"收徒记录(%@)",self.headModel.itemPupilCount],
                                                        [NSString stringWithFormat:@"未毕业(%@)",self.headModel.itemUnGraduateCount],
                                                        [NSString stringWithFormat:@"已毕业(%@)",self.headModel.itemGraduateCount]
                                                        ];

            } else {

                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        } else {

        }

        [self.tableview reloadData];

    } FailedBlock:^(NSError * _Nonnull error) {

        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.tableview errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_ApprenticeList];
        }];
    }];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ApprenticListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ApprenticListCellID" forIndexPath:indexPath];
    [cell fillCellWithModel:self.ApprenticeListArray[indexPath.row]];
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.ApprenticeListArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.backgroundColor = UIColorHex(0xf1f1f1);
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        _tableview.tag = 1000;

        [_tableview registerNib:[UINib nibWithNibName:@"ApprenticListCell" bundle:nil] forCellReuseIdentifier:@"ApprenticListCellID"];

    }
    return _tableview;
}

- (HMSegmentedControl *)segmentedControl {
    if (!_segmentedControl) {

        _segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"收徒记录(X人)", @"未毕业(X人)",@"已毕业(X人)"]];
        //    _segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleArrow;

        _segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        _segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed;

        _segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName:UIColorHex(0x333333), NSFontAttributeName :[UIFont systemFontOfSize:14]};
        _segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName:PP_Default_Color_Red_FF3737,NSFontAttributeName : [UIFont boldSystemFontOfSize:14]};
        _segmentedControl.selectionIndicatorColor = PP_Default_Color_Red_FF3737;
        _segmentedControl.backgroundColor = [UIColor whiteColor];
        _segmentedControl.selectionIndicatorHeight = 2;

    }
    return _segmentedControl;
}

- (NSMutableArray<ApprenticeModel *> *)ApprenticeListArray {

    if (!_ApprenticeListArray) {
        _ApprenticeListArray = [NSMutableArray new];
    }
    return _ApprenticeListArray;
}

- (ApprenticeHeadModel *)headModel {
    if (!_headModel) {
        _headModel = [[ApprenticeHeadModel alloc] init];
    }
    return _headModel;
}
@end
